#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <strings.h>
#include <pthread.h>
#include <cstdio>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"
#include "RingQueue.hpp"
#include "lockGuard.hpp"
#include "Thread.hpp"

namespace ns_server
{
    const static uint16_t default_port = 8080;
    using func_t = std::function<std::string(std::string)>;

    class UdpServer
    {
    public:
        UdpServer(uint16_t port = default_port)
            : port_(port)
        {
            std::cout << "server addr: " << port << std::endl;
            pthread_mutex_init(&lock, nullptr);
            p = new Thread(1, std::bind(&UdpServer::Recv, this));
            c = new Thread(2, std::bind(&UdpServer::Broadcast, this));
        }

        void start()
        {
            // 1.创建套接字接口，打开网络文件
            sock_ = socket(AF_INET, SOCK_DGRAM, 0);
            if (sock_ < 0)
            {
                std::cerr << "create socket error" << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }
            std::cout << "create socket success:" << sock_ << std::endl;

            // 2.绑定IP地址和端口号
            struct sockaddr_in local;
            bzero(&local, sizeof(local));

            local.sin_family = AF_INET;
            local.sin_port = htons(port_);
            // local.sin_addr.s_addr = inet_addr(ip_.c_str());
            local.sin_addr.s_addr = INADDR_ANY;

            if (bind(sock_, (const sockaddr *)&local, sizeof(local)) < 0)
            {
                std::cerr << "bind socket error" << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind socket success:" << sock_ << std::endl;

            c->run();
            p->run();
        }

        void addUser(const std::string &name, const struct sockaddr_in &peer) // 不安全，加锁
        {
            LockGuard lg(&lock);
            onlineuser[name] = peer; // 没有就插入，有就什么都不做
        }

        void Recv()
        {
            char buffer[1024];
            while (true)
            {
                // 1.接收数据
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int n = recvfrom(sock_, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
                if (n > 0)
                {
                    buffer[n] = '\0';
                }
                else
                {
                    continue;
                }
                // std::cout << "get message# " << buffer << std::endl;

                // 2.读取客户端主机信息（只是读取，字节序转换并不会影响结构体本身）
                std::string clientip = inet_ntoa(peer.sin_addr);
                uint16_t clientport = ntohs(peer.sin_port);
                std::cout << clientip << "-" << clientport << "# " << buffer << std::endl;

                // 3.构建用户信息，并检查插入，存在就插入，不存在什么都不做
                std::string name = clientip;
                name += "-";
                name += std::to_string(clientport);
                addUser(name, peer);

                std::string massage = "[" + name + "] >> " +buffer;
                // 4.将数据push到环形队列中
                rq.push(massage);

                // // 3.数据处理
                // // std::string response = service_(buffer);
                //
                // // 4.发送数据
                // // sendto(sock_, response.c_str(), response.size(), 0, (struct sockaddr*)&peer, sizeof(peer));
            }
        }

        // 5.发送数据
        void Broadcast()
        {
            while (true)
            {
                std::string sendstring;
                rq.pop(&sendstring);
                std::vector<struct sockaddr_in> v;
                {
                    LockGuard lg(&lock);
                    for (auto user : onlineuser)
                    {
                        v.push_back(user.second);
                    }
                }
                for (auto user : v)
                {
                    sendto(sock_, sendstring.c_str(), sendstring.size(), 0, (struct sockaddr *)&(user), sizeof(user));
                    std::cout << "Broadcast message to:" << inet_ntoa(user.sin_addr) << " " << sendstring << std::endl;
                }
            }
        }

        ~UdpServer()
        {
            pthread_mutex_destroy(&lock);

            c->join();
            p->join();
            delete c;
            delete p;
        }

    private:
        int sock_;      // socket文件描述符
        uint16_t port_; // port端口号
        // std::string ip_; // ip地址
        // func_t service_;     // 数据处理函数
        std::unordered_map<std::string, struct sockaddr_in> onlineuser; // 所有在线用户
        RingQueue<std::string> rq;
        pthread_mutex_t lock;
        Thread *c;
        Thread *p;
    };
}